package com.example.eventbus

import com.hil.eventbus.Subscription
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

object EventBus {
    private val executorService : ExecutorService = Executors.newCachedThreadPool()
    private val subscriberMap = ConcurrentHashMap<EventType, CopyOnWriteArrayList<Subscription>>()
    private val  methodHunter = SubscriberMethodHunter(subscriberMap)

    fun register(subscriber : Any){
        executorService.execute {
            methodHunter.findSubscribeMethods(subscriber)
        }
    }

    fun unRegister(subscriber : Any){
        executorService.execute {
            methodHunter.removeSubscribeMethods(subscriber)
        }
    }


    fun post(event : IEvent){
        post(event, DEFAULT_TAG)
    }

    fun post(event : IEvent, tag : String){
        val  eventType = EventType(event.javaClass, tag)
        val list = methodHunter.getMatchEventType(eventType)
        list?.let {
            EventDispatcher.dispatcherEvent(event, it)

        }
    }
}